import string
from xml import sax

#We subclass from ContentHandler in order to gain default behaviors
class TreePrintHandler(sax.ContentHandler):
    #A class that handles XML events and draws a tree from the document structure

    def __init__(self):
        #In Python, self is conventionally used as a name of the value
        #That represents the instance on which the method is being invoked
        #This means that you handle instance variables as attributes of self
        self.depth = 0
        self.increment = "  "
        return

    def startDocument(self):
        print "--- [Document]"
        self.depth = self.depth + 1
        return

    def startElement(self, name, attributes):
        #In Python multiplying a string by an Integer repeats the string that
        #many times
        print self.increment*self.depth + "+-- [Element <" + name + ">]"
        self.depth = self.depth + 1
        return

    def endElement(self, name):
        self.depth = self.depth - 1
        return

    def characters(self, text):
        #Only print out any information on this string
        #if it has non-space characters
        if not text.isspace():
            print self.increment*self.depth + "+-- [Text <" + text + ">]"
        return

#A little Python magic that allows this program to run as a stand-alone script
def mainparser(xml_source):
    #Create a new parser instance, using the default XML engine SAX provides
    parser = sax.make_parser()
    #Create an instance of our handler class, which will be registered
    #to receive SAX events
    handler = TreePrintHandler()
    #Pass a string to be parsed, and pass the handler to be registered
    #to receive SAX events.
    sax.parseString(xml_source, handler)
    #At this point, the parser has completed processing, and all events
    #have been dispatched.  We're done.